#!/usr/bin/env python3
"""
nss-pam-ldapd MCP Server

面向 nss-pam-ldapd 软件的 MCP 服务器，提供对 nslcd 服务管理的命令行工具。

MCP tools 列表：
- nslcd_service_restart: 重启 nslcd 服务
- nslcd_service_enable: 启用 nslcd 服务
- nslcd_service_reload: 重载 nslcd 服务
- nslcd_journal_check: 检查 nslcd 服务日志中的错误信息

所有工具返回统一的 JSON 结构：
{
  "success": bool,
  "command": str,
  "exit_code": int,
  "stdout": str,
  "stderr": str
}
"""

import subprocess
import json
from typing import Optional
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("nss-pam-ldapd MCP Server")

@mcp.tool()
def nslcd_service_restart() -> dict:
    """
    重启 nslcd 服务
    
    返回:
        dict: 包含执行结果的 JSON 对象
    """
    command = ["systemctl", "restart", "nslcd"]
    result = subprocess.run(command, capture_output=True, text=True)
    
    return {
        "success": result.returncode == 0,
        "command": " ".join(command),
        "exit_code": result.returncode,
        "stdout": result.stdout,
        "stderr": result.stderr
    }

@mcp.tool()
def nslcd_service_enable() -> dict:
    """
    启用 nslcd 服务
    
    返回:
        dict: 包含执行结果的 JSON 对象
    """
    command = ["systemctl", "enable", "nslcd"]
    result = subprocess.run(command, capture_output=True, text=True)
    
    return {
        "success": result.returncode == 0,
        "command": " ".join(command),
        "exit_code": result.returncode,
        "stdout": result.stdout,
        "stderr": result.stderr
    }

@mcp.tool()
def nslcd_service_reload() -> dict:
    """
    重载 nslcd 服务
    
    返回:
        dict: 包含执行结果的 JSON 对象
    """
    command = ["systemctl", "reload", "nslcd"]
    result = subprocess.run(command, capture_output=True, text=True)
    
    return {
        "success": result.returncode == 0,
        "command": " ".join(command),
        "exit_code": result.returncode,
        "stdout": result.stdout,
        "stderr": result.stderr
    }

@mcp.tool()
def nslcd_journal_check(since_time: Optional[str] = None) -> dict:
    """
    检查 nslcd 服务日志中的错误信息
    
    参数:
        since_time: 日志起始时间（可选），格式如 "2024-01-01 10:00:00"
    
    返回:
        dict: 包含执行结果的 JSON 对象
    """
    command = ["journalctl", "-u", "nslcd"]
    
    if since_time:
        command.extend(["--since", since_time])
    
    # 过滤错误信息，排除 DEBUG/INFO/WARNING 级别和特定 SASL 错误
    grep_command = ["grep", "-i", "fail\\|error"]
    result1 = subprocess.run(command, capture_output=True, text=True)
    result2 = subprocess.run(grep_command, input=result1.stdout, capture_output=True, text=True)
    result3 = subprocess.run(["grep", "-v", "-i", "DEBUG\\|INFO\\|WARNING"], input=result2.stdout, capture_output=True, text=True)
    result4 = subprocess.run(["grep", "-v", "_sasl_plugin_load failed on sasl_canonuser_init"], input=result3.stdout, capture_output=True, text=True)
    
    return {
        "success": result4.returncode == 0 and len(result4.stdout.strip()) == 0,
        "command": f"{' '.join(command)} | {' '.join(grep_command)} | grep -v -i 'DEBUG\\|INFO\\|WARNING' | grep -v '_sasl_plugin_load failed on sasl_canonuser_init'",
        "exit_code": result4.returncode,
        "stdout": result4.stdout,
        "stderr": result4.stderr
    }

if __name__ == "__main__":
    mcp.run()